#include "userselection.h"
#include "ui_userselection.h"
#include <QInputDialog>
#include <QFile>
#include <QDir>
#include <QTextStream>
#include <QMessageBox>
#include <iostream>

UserSelection::UserSelection(QWidget *parent) :
    QWidget(parent),
    m_ui(new Ui::UserSelection)
{
    m_ui->setupUi(this);

    QFile file("users/.users");
    if (!file.open(QIODevice::ReadOnly))
        return;
    while (!file.atEnd())
    {
        QString user = file.readLine().trimmed();
        m_ui->userList->addItem(user);
        existing += user;
    }
}

UserSelection::~UserSelection()
{
    delete m_ui;
}

void UserSelection::start()
{
    emit userSelected(m_ui->userList->currentItem()->text());
}
/*
this function is used to create the user files
*/
void UserSelection::createUser()
{
    bool ok;
    QString newUser = QInputDialog::getText(this,"User Creation",
                          tr("Enter the new user name:"),
                          QLineEdit::Normal, "user", &ok);//setting up the dialog for the username
    if (!ok)
        return;
    else if (newUser.isEmpty() || existing.contains(newUser))//check to see if the username already exists
    {
        QMessageBox msgBox(this);
        msgBox.setText("You're trying to create a user that already exists or an empty user name, please try again!");//message output if user already exists
        msgBox.exec();//show the box
        return;
    }

    QFile file("users/.users");//ceating the path for the user files
    if (!file.open(QIODevice::ReadWrite | QIODevice::Append))
        return;

    QTextStream users(&file);//opening the user file
    m_ui->userList->addItem(newUser);//adding the user to the list
    existing += newUser;//apending the user to the exixting list

    QFile userfile(QString("users/").append(newUser));//opening users own file
    if (!userfile.open(QIODevice::WriteOnly | QIODevice::Truncate))//checking the write permissoins to see if there is an error writing
    {
        QMessageBox msgBox(this);//creating a messagebox
        msgBox.setText("Error creating the user's progress file!");//setting the error message
        msgBox.exec();//showing the box
        return;
    }
    userfile.close();//closing the file writer

    users << newUser.append("\n");
}

/*
function used to delete the user files from the list and the HDD
*/
void UserSelection::deleteUser()
{
    int ret;
    QMessageBox msgBox;
        msgBox.setText("You're trying to delete a user, the user's progress will be lost.");//message output if a user is being deleted
        msgBox.setInformativeText("Do you want to proceed?");//asked if you want to procced
        msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
        msgBox.setDefaultButton(QMessageBox::Ok);
        ret = msgBox.exec();//showing box

    if (ret != QMessageBox::Ok)
        return;
    QListWidgetItem* wi = m_ui->userList->takeItem(m_ui->userList->currentRow());//creating the list item of the username
    QFile file("users/.users");//creatring the file path

    existing.removeAt(existing.indexOf(wi->text()));//remove the user from the list

    QDir dir("users");
    if (!dir.exists())
        std::cout <<"Cannot find the example directory\n";
    if (!dir.exists(wi->text()))
        std::cout <<"Cannot find the example file\n";
    dir.remove(QString(wi->text()));

    if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate))
        std::cout << "HELP!!\n";
    QTextStream out(&file);//opening the file write stream
    foreach (QString str, existing)
        out << str.append("\n");//writing to the file
}
/*
function used when user skips the user selection view
*/
void UserSelection::skippingUser()
{
    emit skipped();//emits this signal
}

void UserSelection::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}
